package com.hisan.freeride.home.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;

import com.github.library.BaseQuickAdapter;
import com.github.library.listener.OnItemClickListener;

import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.base.BaseAppLication;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CacheUtils;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.view.MyGridLayoutManager;
import com.hisan.freeride.databinding.CityItemBinding;
import com.hisan.freeride.home.adapter.CityRecyclerAdapter;
import com.hisan.freeride.home.model.CityModel;
import com.hisan.freeride.home.model.CitySite;
import com.lzy.okgo.OkGo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

/**
 * 城市选择
 * Created by admin on 2017/5/20.
 */

public class Select_CityActivity extends BaseActivity<CityItemBinding> {
    private CityRecyclerAdapter adapter;
    private Intent intent;
    private String name="城市";
    //取消时间
    public static final long TIME_SPACE = 2000;
    private long clickTime;
    private List<CityModel>cityModels;

    @Override
    protected int getLayoutId() {
        return  R.layout.city_item;
    }

    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        MyGridLayoutManager myGridLayoutManager = new MyGridLayoutManager(this,2);
        mBinding.recyCity.setLayoutManager(myGridLayoutManager);
        adapter = new CityRecyclerAdapter(new ArrayList<>(0));
        mBinding.recyCity.setAdapter(adapter);
        Bundle bundle=getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            name=bundle.getString("name");
            if (name.equals("首页")){
                mBinding.topBack.setVisibility(View.GONE);
            }else{
                mBinding.topBack.setVisibility(View.VISIBLE);
                mBinding.topBack.setOnClickListener(v -> finishActivity(true));
            }
        }else {
            mBinding.topBack.setVisibility(View.VISIBLE);
            mBinding.topBack.setOnClickListener(v -> finishActivity(false));
        }

    }

    @Override
    protected void initEvent() {
        mBinding.recyCity.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                CityModel cityModel= (CityModel) baseQuickAdapter.getItem(position);
                if (!CollectionUtils.isNullOrEmpty(cityModel)){
                    BaseAppLication.getInstance().setCityid(cityModel.getId());
                    if (name.equals("首页")){
                        Bundle bundle=new Bundle();
                        bundle.putString("city",cityModel.getName());
                        BaseAppLication.getInstance().setCityid(cityModel.getId());
                        CitySite citySite=new CitySite();
                        citySite.setName(cityModel.getName());
                        CacheUtils.getInstance().put("city",cityModel.getName());
                        citySite.setId(cityModel.getId());
                        BaseAppLication.getInstance().getCityManger().insert(citySite);
                        startActivityForResult(MainActivity.class,0,bundle,false);
                    }else {
                        if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                        intent.putExtra("city",cityModel.getName());
                        BaseAppLication.getInstance().setCityid(cityModel.getId());
                        BaseAppLication.getInstance().getCityManger().claer();
                        CitySite citySite=new CitySite();
                        citySite.setName(cityModel.getName());
                        citySite.setId(cityModel.getId());
                        BaseAppLication.getInstance().getCityManger().insert(citySite);
                        setResult(96,intent);
                        finishActivity(false);
                    }
                }
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<List<Object>>get(AppConfig.GetCity)
                .tag(this)
                .execute(new DialogCallback<List<Object>>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<Object>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            showData();
                            cityModels=new ArrayList<>();
                            JSONArray array=new JSONArray(response.body());
                            if (array.length()>0){
                                for (int i=0;i<array.length();i++){
                                    try {
                                        JSONObject json=array.getJSONObject(i);
                                        int id=json.getInt("id");
                                        String name=json.getString("name");
                                        CityModel cityModel=new CityModel();
                                        cityModel.setId(id);
                                        cityModel.setName(name);
                                        cityModels.add(cityModel);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                              adapter.setNewData(cityModels);
                            }

                        }
                    }
                });

    }

    //监听物理返回键（判断侧拉框是否打开）
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (name.equals("首页")){
                exit();
            }else {
                finishActivity(true);
            }
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    /**
     * if click time space < TIME_SPACE, app will exit
     */
    private void exit() {
        if ((System.currentTimeMillis() - clickTime) > TIME_SPACE) {
            showToast("再点一次退出顺风车");

            clickTime = System.currentTimeMillis();
            return;
        }
        //退出应用
        appManger.AppExit(this);
    }
}
